<template>
  <n-form
      :model="formData"
      :rules="formRules"
      ref="formInstance"
      label-placement="left"
      :label-width="SlashAppContext.getCoefficient()*80 + 'px'">
    <n-grid x-gap="12" :cols="2" responsive="self">
      <n-gi :span="resource === 'baseinfo' ? 1 : 2">
        <n-form-item label="头像" path="nickName">
          <n-avatar :size="120" :src="avatar" :fallbackSrc="avatarFallbackSrc" @click="onSelectHeadImg">
            <span v-if="avatar.length==0">点击选择图片</span>
          </n-avatar>
        </n-form-item>
      </n-gi>
      <n-gi v-if="resource === 'baseinfo'">
        <n-form-item label="密码" style="margin-top: 80px;">
          <n-button @click="handleModifyPwd">修改密码</n-button>
        </n-form-item>
      </n-gi>
      <n-gi>
        <n-form-item label="昵称" path="nickName">
          <n-input clearable v-model:value="formData.nickName" placeholder="请输入昵称"/>
        </n-form-item>
      </n-gi>
      <n-gi>
        <n-form-item label="姓名" path="username">
          <n-input clearable v-model:value="formData.username" placeholder="请输入姓名"/>
        </n-form-item>
      </n-gi>
      <n-gi>
        <n-form-item label="账号" path="account">
          <n-input clearable v-model:value="formData.account" placeholder="请输入账号"/>
        </n-form-item>
      </n-gi>
      <n-gi>
        <n-form-item label="电话" path="phone">
          <n-input ref="phoneRef" clearable v-model:value="formData.phone" placeholder="请输入联系电话" @blur="handleBlur" @focus="handleFocus">
          </n-input>
        </n-form-item>
      </n-gi>
      <n-gi>
        <n-form-item label="身份证号" path="idCard">
          <n-input clearable v-model:value="formData.idCard" placeholder="请输入身份证号"/>
        </n-form-item>
      </n-gi>
      <n-gi>
        <n-form-item label="性别" path="sex">
          <n-radio-group v-model:value="formData.sex">
            <n-space>
              <n-radio :key="it.value" v-for="it in sexOptions" :value="it.value" :label="it.label"/>
            </n-space>
          </n-radio-group>
        </n-form-item>
      </n-gi>

      <n-gi>
        <n-form-item label="邮箱" path="email">
          <n-input clearable v-model:value="formData.email" placeholder="请输入邮箱"/>
        </n-form-item>
      </n-gi>

      <n-gi>
        <n-form-item label="账号状态" path="enabled">
          <n-radio-group v-model:value="formData.isLock" :disabled="resource === 'baseinfo'">
            <n-space>
              <n-radio :key="it.value" v-for="it in isLockOptions" :value="it.value" :label="it.label"/>
            </n-space>
          </n-radio-group>
        </n-form-item>
      </n-gi>
      <n-gi>
        <n-form-item label="部门" path="fkDeptCode">
          <n-tree-select placeholder="请选择部门" filterable key-field="fullDeptCode" label-field="deptName"
                         :default-value="formData.fkDeptCode"
                         :options="deptOptions" v-model:value="formData.fkDeptCode" @update:value="onSelectDept"
                         default-expand-all
                         :disabled="resource === 'baseinfo'"
          />
        </n-form-item>
      </n-gi>
      <n-gi>
        <n-form-item label="岗位" path="fkPostId">
          <n-select placeholder="请选择岗位" v-model:value="formData.fkPostId" :options="postOptions" :disabled="resource === 'baseinfo'"/>

        </n-form-item>
      </n-gi>
      <n-gi :span="2">
        <n-form-item label="角色" path="fkDeptCode">
          <n-select placeholder="请选择角色" multiple v-model:value="formData.roleCodeList" :options="roleOptions" :disabled="resource === 'baseinfo'"/>
        </n-form-item>
      </n-gi>
    </n-grid>
  </n-form>
</template>
<script lang="ts">
import {onMounted, ref} from "vue";
import {getDeptOptions, enabledOptions, formRules, isLockOptions, getPostOptions, getRoleOptions, sexOptions} from "./Service";
import httpApi from "./httpApi";
import {FormInst} from "naive-ui";
import {checkFormData, SlashAppContext} from "slash-admin";
import {Layer} from "slash-layer";
import {AuthTbRoleApi} from "@/views/AuthTbRole";
import { PropType, watch } from "vue";
import UpdatePassword from "./UpdatePassword.vue"
import { Eye, EyeOff } from "@vicons/ionicons5"
import Utils from "@/utils";

export default {
  props: {
    id: {
      type: [String, Number],
      default: null
    },
    readMode: {
      type: [String],
      default: "read"
    },
    resource: {
      type: String as PropType<'usermanage' | 'baseinfo'>,
      default: 'usermanage'
    }
  },
  components: {
    Eye,
    EyeOff
  },
  setup: function (props) {
    const formInstance = ref<FormInst | null>(null);
    const formData = ref<any>({
      id: props.id,
      enabled: 1
    });
    const roleOptions = ref<any>()
    const postOptions = ref<any>()
    const deptOptions = ref<any>()
    const hidePhone = ref(true)
    const phoneRef = ref()
    const phoneNumber = ref()
    const reg = /^(\d{3})\d{4}(\d*)$/;
    const avatar = ref<string>("");
    const avatarFallbackSrc = Utils.getImageUrl('errorImgWhite.png');

    const init = async () => {
      if (props.id) {
        let msg = await httpApi.selectById(props.id);
        formData.value = msg.data;
        let {data} = await AuthTbRoleApi.selectListByUserId(props.id);
        const result = data.map(it => {
          return it.roleCode;
        })
        formData.value.roleCodeList = result;
      }
      if (formData.value.headImgAddress) {
        avatar.value = SlashAppContext.fileBaseUrl() + formData.value.headImgAddress;
      }
      phoneNumber.value = formData.value.phone
      formData.value.phone = formData.value.phone.replace(reg, '$1****$2')
      console.log(formData)
    };

    async function onSelectDept(row) {
      formData.fkDeptCode = row;
    }

    async function onSelectHeadImg(row) {
      const file: any = await Layer.selectFile({
        accept: [".jpg", ".png", ".jpeg"]
      })
      if (file.length == 0) {
        Layer.error("请选择一张图片");
        return;
      }
      const {data} = await httpApi.doUploadHeadImg([file[0]]);
      console.log("计算结果:", SlashAppContext.fileBaseUrl() + data[0].uri)
      avatar.value = SlashAppContext.fileBaseUrl() + data[0].uri;
      formData.value.headImgAddress = data[0].uri;
    }
    function handleModifyPwd() {
      Layer.createForm({
        content: {
          component: UpdatePassword
        },
        title: "修改密码",
        autoInfo: false,
        position: {
          height: 320,
          width: 400
        }
      } as any);
    }

    function handleBlur(e: any) {
      phoneNumber.value = formData.value.phone
      formData.value.phone = formData.value.phone.replace(reg, '$1****$2')
    }
    function handleFocus(e: any) {
      formData.value.phone = phoneNumber.value
    }

    const doSubmit = async () => {
      await checkFormData(formInstance);
      return httpApi.doSaveEntity(Object.assign({}, formData.value, {phone: phoneNumber.value}));
    };
    const doUpdate = async () => {
      await checkFormData(formInstance);
      return httpApi.doUpdateEntity(Object.assign({}, formData.value, {phone: phoneNumber.value}));
    };
    onMounted(async () => {
      // init();
      roleOptions.value = await getRoleOptions()
      postOptions.value = await getPostOptions()
      deptOptions.value = await getDeptOptions()
      console.log('roleOptions', roleOptions.value)
    });

    watch(
      () => props,
      () => {
        if (props.id) {
          init();
        }
      },
      { immediate: true, deep: true }
    )
    return {
      avatar,
      avatarFallbackSrc,
      isLockOptions,
      onSelectHeadImg,
      postOptions,
      enabledOptions,
      sexOptions,
      roleOptions,
      deptOptions,
      onSelectDept,
      formData,
      formInstance,
      formRules,
      doSubmit,
      doUpdate,
      handleModifyPwd,
      hidePhone,
      phoneRef,
      handleBlur,
      handleFocus,
      SlashAppContext
    };
  },
};
</script>

<style lang="less" scoped></style>
